package com.th.campusmatchbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.th.campusmatchbackend.common.ErrorCode;
import com.th.campusmatchbackend.exception.BusinessException;
import com.th.campusmatchbackend.model.domain.User;
import com.th.campusmatchbackend.model.request.UpdateTagRequest;
import com.th.campusmatchbackend.model.request.UserQueryRequest;
import com.th.campusmatchbackend.service.UserService;
import com.th.campusmatchbackend.mapper.UserMapper;
import com.th.campusmatchbackend.utils.AlgorithmUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.util.Pair;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.th.campusmatchbackend.contant.UserContant.ADMIN_ROLE;
import static com.th.campusmatchbackend.contant.UserContant.USER_LOGIN_STATE;
import static com.th.campusmatchbackend.utils.StringUtils.stringJsonListToLongSet;

/**
 * 用户服务实现类
 *
* @author taoha
* @description 针对表【user】的数据库操作Service实现
* @createDate 2023-09-26 20:03:39
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Resource
    private  UserMapper userMapper;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "th";

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword,String username) {
        //1.校验
        if(StringUtils.isAnyBlank(userAccount,userPassword,checkPassword,username)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if(userAccount.length()<4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账号过短");
        }
        if(userPassword.length()<8||checkPassword.length()<8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户密码过短");
        }



        //账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if(matcher.find()){
            return -1;
        }
        //密码和校验密码相同
        if(!userPassword.equals(checkPassword)){
            return -1;
        }
        //账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if(count>0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号重复");
        }

        //2.加密
        String  encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        //3.插入数据
        User   user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUsername(username);
        boolean saveResult = this.save(user);
        if(!saveResult){
            return -1;
        }
        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1.校验
        if(StringUtils.isAnyBlank(userAccount,userPassword)){
            return  null;
        }
        if(userAccount.length()<4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号不少于4位");
        }
        if(userPassword.length()<8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码不少于8位");
        }

        //账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if(matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号不能包含特殊字符");
        }

        //2.加密
        String  encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        //查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        queryWrapper.eq("userPassword",encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        if(user==null){
            log.info("user login failed,userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.NULL_ERROR,"账号或密码错误");
        }

        //3.用户脱敏
       User safetyUser = getSafetyUser(user);

        //4.记录用户登录态
        request.getSession().setAttribute(USER_LOGIN_STATE,safetyUser);
        return safetyUser;
    }


    /**
     * 用户脱敏
     * @param originUser
     * @return
     */
    @Override
    public  User getSafetyUser(User originUser){
            if(originUser==null){
                return null;
            }
            User safetyUser = new User();
            safetyUser.setId(originUser.getId());
            safetyUser.setUsername(originUser.getUsername());
            safetyUser.setUserAccount(originUser.getUserAccount());
            safetyUser.setAvatarUrl(originUser.getAvatarUrl());
            safetyUser.setPhone(originUser.getPhone());
            safetyUser.setEmail(originUser.getEmail());
            safetyUser.setUserRole(originUser.getUserRole());
            safetyUser.setUserStatus(originUser.getUserStatus());
            safetyUser.setCreateTime(originUser.getCreateTime());
            safetyUser.setGender(originUser.getGender());
            safetyUser.setTags(originUser.getTags());
            safetyUser.setProfile(originUser.getProfile());
            safetyUser.setUserIds(originUser.getUserIds());
            return safetyUser;
    }

    /**
     * 用户注销
     * @param request
     */
    @Override
    public int userLogout(HttpServletRequest request) {
        //移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;

    }

    /**
     * 根据标签搜索用户
     * @param tagNameList  用户要搜索的标签
     * @return
     */
    @Override
    public List<User> searchUsersByTags(List<String> tagNameList){

        if(CollectionUtils.isEmpty(tagNameList)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }


        return sqlSearch(tagNameList);

    }

    @Override
    public int updateUser(User user, User loginUser,HttpServletRequest request) {
        long userId  = user.getId();
        if(userId<=0){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //2.校验权限
        //2.1 管理员可以更新任意信息，用户只能更新自己的信息
        if(!isAdmin(loginUser)&&userId != loginUser.getId()){
            throw new BusinessException(ErrorCode.NULL_AUTH);
        }

        User oldUser  = userMapper.selectById(user.getId());
        if(oldUser==null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        int res = userMapper.updateById(user);
        User newUser = userMapper.selectById(user.getId());
        //3.用户脱敏
        User safetyUser = getSafetyUser(newUser);

        //4.记录用户登录态
        request.getSession().setAttribute(USER_LOGIN_STATE,safetyUser);
        return res;

    }

    @Override
    public User getCurrentUser(HttpServletRequest request) {

        if(request==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Object userobj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User  currentUser = (User) userobj;
        if(currentUser==null){
            throw new BusinessException(ErrorCode.NULL_LOGIN);
        }
        return currentUser;
    }

    /**
     * 是否为管理员
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        //仅管理员可查询
        Object userobj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User)userobj;
        if(user == null|| user.getUserRole() != ADMIN_ROLE){
            return false;
        }
        return  true;
    }

    /**
     * 是否为管理员
     * @param loginUser
     * @return
     */
    @Override
    public boolean isAdmin(User loginUser) {
        //仅管理员可查询
        if(loginUser == null|| loginUser.getUserRole() != ADMIN_ROLE){
            return false;
        }
        return  true;
    }

    @Override
    public List<User> matchUsers(long num, User loginUser) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","tags");
        queryWrapper.isNotNull("tags");

        List<User> userList = this.list(queryWrapper);
        String tags = loginUser.getTags();
        Gson gson = new Gson();
        List<String> tagList = gson.fromJson(tags, new TypeToken<List<String>>() {
        }.getType());
        if (CollectionUtils.isEmpty(tagList)) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "请先添加标签");
        }
        //用户列表的下标 => 相似度
        List<Pair<User,Long>> list = new ArrayList<>();
        //依次计算所有用户和当前用户的相似度
        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            String userTags = user.getTags();
            //无标签或者为当前用户自己
            if (StringUtils.isBlank(userTags) || Objects.equals(user.getId(), loginUser.getId())) {
                System.out.print("执行continue方法");
                System.out.println("该用户的id为"+user.getId()+"该用户的便签为"+userTags);
                continue;
            }
            List<String> userTagList = gson.fromJson(userTags, new TypeToken<List<String>>() {
            }.getType());
            System.out.println("没进入continue的userid为"+user.getId());
            //计算分数
            long distance = AlgorithmUtils.minDistance(tagList, userTagList);
            list.add(new Pair<>(user, distance));
        }
        //按编辑距离由小到大排序
        List<Pair<User, Long>> topUserPairList = list.stream()
                .sorted((a, b) -> (int) (a.getValue() - b.getValue()))
                .limit(num)
                .collect(Collectors.toList());

        for (Pair<User, Long> pair : topUserPairList) {
            System.out.println("用户：" + pair.getKey().getId() + " 分数：" + pair.getValue());
        }

        //原本顺序的userId列表
        List<Long> userIdList = topUserPairList
                .stream()
                .map(pair -> pair.getKey().getId())
                .collect(Collectors.toList());
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id",userIdList);
        // 1 , 3, 2
        //User1、 User2、 User3
        //1 => User1, 2 => User2, 3 => User3
        //存一个对应关系
        Map<Long, List<User>> userIdUserListMap = this.list(userQueryWrapper)
                .stream()
                .map(user -> getSafetyUser(user))
                .collect(Collectors.groupingBy(User::getId));
        List<User> finalUserList = new ArrayList<>();
        for (Long userId : userIdList) {
            finalUserList.add(userIdUserListMap.get(userId).get(0));
        }
        return finalUserList;
    }

    @Override
    public List<User> getFriendsById(User currentUser) {
        User loginUser = this.getById(currentUser.getId());
        Set<Long> friendsId = stringJsonListToLongSet(loginUser.getUserIds());
        return friendsId.stream().map(user -> this.getSafetyUser(this.getById(user))).collect(Collectors.toList());
    }

    @Override
    public List<User> searchFriend(UserQueryRequest userQueryRequest, User currentUser) {
        String searchText = userQueryRequest.getSearchText();
        User user = this.getById(currentUser.getId());
        Set<Long> friendsId = stringJsonListToLongSet(user.getUserIds());
        List<User> users = new ArrayList<>();
        Collections.shuffle(users);
        friendsId.forEach(id -> {
            User u = this.getById(id);
            if (u.getUsername().contains(searchText)) {
                users.add(u);
            }
        });
        return users;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<User> matchGeoUsers(int num, Point userPoint, int matchRange, User loginUser) {
        String GeoKey = "taohahu:matchGeo:Coordinate";
        Long userId = loginUser.getId();
        // 先删除缓存中之前的定位信息
        if (userId < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String newUserId = userId + "";
        Map<String, Point> points = new HashMap<>();
        points.put(newUserId, userPoint);
        Long result = redisTemplate.opsForGeo().add(GeoKey, points);

        if (result == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "添加当前用户地址失败");
        }

        // 查询范围内的用户，如果没有随机推送，如果有则返回一定数量的用户
        Circle aimPoint = new Circle(userPoint, matchRange);
        // 返回信息的规则，例如距离，排序，条数等
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands
                .GeoRadiusCommandArgs
                .newGeoRadiusArgs()
                .includeDistance()
                .includeCoordinates()
                .sortAscending()
                .limit(num);

        GeoResults<RedisGeoCommands.GeoLocation<String>> radius = redisTemplate.opsForGeo().radius(GeoKey, aimPoint, args);
        // 获取到存储了id，坐标，距离的集合
        List<Long> GeoMatchUsersIds = new ArrayList<>();
        if (radius != null) {
            List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = radius.getContent();
            for (GeoResult<RedisGeoCommands.GeoLocation<String>> geoLocationGeoResult : content) {
                String getMatchUserId = geoLocationGeoResult.getContent().getName();
                GeoMatchUsersIds.add(Long.valueOf(getMatchUserId));
            }
        }

        if (GeoMatchUsersIds.isEmpty()) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "附近没有人匹配");
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id", GeoMatchUsersIds);
        List<User> userList = this.list(userQueryWrapper);

        return userList.stream().map(this::getSafetyUser).collect(Collectors.toList());
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateTagById(UpdateTagRequest updateTag, User currentUser ,HttpServletRequest request) {

        long id = updateTag.getId();
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该用户不存在");
        }
        Set<String> newTags = updateTag.getTagList();
        if (newTags.size() > 12) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "最多设置12个标签");
        }
        if (!isAdmin(currentUser) && id != currentUser.getId()) {
            throw new BusinessException(ErrorCode.NULL_AUTH, "无权限");
        }

        User user = userMapper.selectById(id);
        Gson gson = new Gson();
        Set<String> oldTags = gson.fromJson(user.getTags(), new TypeToken<Set<String>>() {
        }.getType());
        Set<String> oldTagsCapitalize = toCapitalize(oldTags);
        Set<String> newTagsCapitalize = toCapitalize(newTags);

        // 添加 newTagsCapitalize 中 oldTagsCapitalize 中不存在的元素
        oldTagsCapitalize.addAll(newTagsCapitalize.stream().filter(tag -> !oldTagsCapitalize.contains(tag)).collect(Collectors.toSet()));
        // 移除 oldTagsCapitalize 中 newTagsCapitalize 中不存在的元素
        oldTagsCapitalize.removeAll(oldTagsCapitalize.stream().filter(tag -> !newTagsCapitalize.contains(tag)).collect(Collectors.toSet()));
        String tagsJson = gson.toJson(oldTagsCapitalize);
        user.setTags(tagsJson);
        //3.用户脱敏
        User safetyUser = getSafetyUser(user);

        //4.记录用户登录态
        request.getSession().setAttribute(USER_LOGIN_STATE,safetyUser);
        return userMapper.updateById(user);
    }

    @Override
    public boolean deleteFriend(User currentUser, Long id) {
        User loginUser = this.getById(currentUser.getId());
        User friendUser = this.getById(id);
        Set<Long> friendsId = stringJsonListToLongSet(loginUser.getUserIds());
        Set<Long> fid = stringJsonListToLongSet(friendUser.getUserIds());
        friendsId.remove(id);
        fid.remove(loginUser.getId());
        String friends = new Gson().toJson(friendsId);
        String fids = new Gson().toJson(fid);
        loginUser.setUserIds(friends);
        friendUser.setUserIds(fids);
        return this.updateById(loginUser) && this.updateById(friendUser);
    }

    /**
     * 利用sql查询
     * @param tagNameList 用户要搜索的标签
     * @return
     */
    public List<User> sqlSearch(List<String> tagNameList){

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //拼接
        //like '%Java%'  and  like '%C++%'
        for(String tagList:tagNameList){
            queryWrapper = queryWrapper.like("tags",tagList);
        }
        List<User> userList = userMapper.selectList(queryWrapper);

        return userList.stream().map(this::getSafetyUser).collect(Collectors.toList());

    }

    /**
     * 利用内存查询
     * @param tagNameList 用户要搜索的标签
     * @return
     */
    public List<User> memorySearch(List<String> tagNameList){

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        long starTime = System.currentTimeMillis();

        List<User> userList = userMapper.selectList(queryWrapper);

        Gson gson = new Gson();
        userList.stream().filter(user -> {
            String tagsStr = user.getTags();
            Set<String> tempTagNameSet = gson.fromJson(tagsStr, new TypeToken<Set<String>>() {}.getType());
            tempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());
            for(String tageName: tagNameList){
                if(!tempTagNameSet.contains(tageName)){
                    return  false;
                }
            }
            return true;
        }).map(this::getSafetyUser).collect(Collectors.toList());
        log.info("memory query time = " + (System.currentTimeMillis() - starTime));
        return userList;


    }

    /**
     * String类型集合首字母大写
     *
     * @param oldSet 原集合
     * @return 首字母大写的集合
     */
    private Set<String> toCapitalize(Set<String> oldSet) {
        return oldSet.stream().map(StringUtils::capitalize).collect(Collectors.toSet());
    }



}





